<script setup lang="ts">
import { ref, onMounted } from "vue";
import * as PIXI from "pixi.js";
import { G_throttle } from "src/pioneers/Gab/utils/tool";

const dom = ref<HTMLDivElement>();
const PixelLayer = ref<HTMLDivElement>();
const color = ref("rgba(255,255,255,1)");
const grids = ref(21);
let app: PIXI.Application;

const obs = new ResizeObserver(() => {
  PixelLayer.value?.parentElement;
  if (PixelLayer.value) {
    const { clientHeight, clientWidth } = PixelLayer.value.parentElement!;
    const size = Math.min(clientHeight, clientWidth);
    PixelLayer.value.style.height = PixelLayer.value.style.width = `${size}px`;
    if (app) {
      resetGrid();
      app.view.width = Number(size);
      app.view.height = Number(size);
      app.resize();
      app.renderer.resize(size, size);
    } else {
      app = new PIXI.Application({
        resizeTo: PixelLayer.value,
        resolution: window.devicePixelRatio,
        autoDensity: true,
        // antialias: true,
        backgroundAlpha: 0,
      });
      app.view.style!.width = "100%";
      app.view.style!.height = "100%";
      PixelLayer.value!.appendChild(app.view as unknown as Node);

      app.stage.addChild(container);

      container.addChild(piece);
      resetGrid();
    }
  }
});
const container = new PIXI.Container();
container.eventMode = "static";
const piece = new PIXI.Graphics();
piece.eventMode = "static";
function initGrid() {
  container.removeChildren(0);
  for (let row = 0; row < grids.value; row++) {
    for (let col = 0; col < grids.value; col++) {
      const piece = new PIXI.Graphics();
      piece.eventMode = "static";
      const G_color = (row + col) % 2 ? "#FFFFFF" : "#D9D9D9";
      const size = PixelLayer.value!.clientWidth / grids.value;
      piece.beginFill(G_color).drawRect(size * row, size * col, size, size);
      piece.on("pointerdown", () => {
        piece
          .beginFill(color.value)
          .drawRect(size * row, size * col, size, size);
      });
      container.addChild(piece);
    }
  }
}
const resetGrid = G_throttle(initGrid, 100);

onMounted(() => {
  obs.observe(document.body);
});
</script>

<template>
  <div class="Gab-Pixel h-full w-full flex flex-col" ref="dom">
    <div class="w-full h-20 flex justify-center items-center gap-10">
      <div class="flex justify-center items-center gap-2">
        <div class="label">尺寸</div>
        <el-input-number
          v-model="grids"
          :min="21"
          :max="42"
          @change="resetGrid"
        />
      </div>
      <div class="flex justify-center items-center gap-2">
        <div class="label G-color-label">颜色</div>
        <el-color-picker v-model="color" show-alpha />
      </div>
    </div>
    <div class="flex-auto box-border p-5">
      <div class="w-full h-full flex justify-center items-center">
        <div ref="PixelLayer" class="layer"></div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.layer {
  position: absolute;
}

</style>
